package com.jayanslow.lighting.server.dmx;

public class FadeAction {
	private DmxChannel channel;
	private int target;
	private int change;
	private boolean increase;
	
	//Constructor, requires channel, 16-bit target DMX value and 16-bit change per tick for DMX value
	public FadeAction(DmxChannel c, int t, int ch) throws OverflowException {
		channel = c;
		if (t > 0xff00 || t < 0x0000) throw new OverflowException("Target value must be between 0x0000 and 0xff00");
		target = t;
		if (ch > 0xff00 || ch < 0xffff0100 || ch == 0) throw new OverflowException("Magnitude of change must be between 0x0001 and 0xff00");
		change = ch;
		if (change > 0) {
			increase = true;
		} else if (change < 0) {
			increase = false;
		} else {
			increase = true;
			target = c.getValue16();
		}
	}
	//Increments/decrements current value by the specified value, until it reaches or overshoots the target value, where the class stops
	public boolean tick() {
		int n = channel.getValue16() + change;
		if ((increase && n >= target) || (!increase && n <= target)) {
			channel.stopFade(true);
			return true;
		} else {
//			System.out.println(Integer.toHexString(n));
			try {
				channel.setValue16(n,false);
			} catch (OverflowException e) { }
			return false;
		}
	}
	
	//Gets the 16-bit target value
	public int getTarget() {
		return target;
	}
}
